#!/bin/bash

# quic_tunnel 一键部署脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# ========== 公共函数部分 ==========

# 安全停止服务
safe_stop_service() {
    log_info "安全停止现有服务..."
    
    if systemctl is-active --quiet quic_tunnel 2>/dev/null; then
        log_info "停止systemd服务..."
        systemctl stop quic_tunnel
        sleep 2
    fi
    
    if pgrep -f "quic_tunnel" > /dev/null; then
        log_info "停止quic_tunnel进程..."
        pkill -f "quic_tunnel" || true
        sleep 2
        pkill -9 -f "quic_tunnel" 2>/dev/null || true
    fi
}

# 完全清理服务
complete_cleanup() {
    log_info "开始完全清理..."
    
    safe_stop_service
    
    if systemctl is-enabled --quiet quic_tunnel 2>/dev/null; then
        log_info "禁用systemd服务..."
        systemctl disable quic_tunnel
    fi
    
    if [ -f "/etc/systemd/system/quic_tunnel.service" ]; then
        log_info "移除systemd服务文件..."
        rm -f /etc/systemd/system/quic_tunnel.service
    fi
    
    systemctl daemon-reload
    systemctl reset-failed
    
    if [ -d "/root/quic_tunnel" ]; then
        log_info "删除程序目录 /root/quic_tunnel..."
        rm -rf /root/quic_tunnel
        log_info "✓ 程序目录已删除"
    else
        log_info "程序目录不存在，跳过删除"
    fi
    
    log_info "✓ 完全清理完成"
}

# 检查quic_tunnel目录是否存在
check_quic_dir() {
    if [ ! -d "/root/quic_tunnel" ]; then
        log_error "quic_tunnel目录不存在，请先部署服务"
        return 1
    fi
    return 0
}

# 下载必要文件
download_files() {
    local target_dir="$1"
    mkdir -p "$target_dir"
    cd "$target_dir"
    
    if [ ! -f "quic_tunnel" ]; then
        log_info "下载quic_tunnel程序..."
        curl -o quic_tunnel 'http://qq-sdk.oss-us-west-1.aliyuncs.com/xcpro/quic_tunnel'
        chmod +x quic_tunnel
    else
        log_info "quic_tunnel程序已存在，跳过下载"
    fi
    
    if [ ! -f "ip4.dat" ]; then
        log_info "下载ip4.dat..."
        curl -o ip4.dat 'http://ipdatacloud-bin.oss-cn-hongkong.aliyuncs.com/ip4.dat'
    else
        log_info "ip4.dat已存在，跳过下载"
    fi
    
    cd ..
}

# 创建配置文件
create_config() {
    local cluster="$1"
    local server_vendor="$2"
    local region="$3"
    local tun_nats_url="$4"
    
    cd /root/quic_tunnel
    
    log_info "创建sdk_tun.ini..."
    cat > sdk_tun.ini << EOF
[module]
Cluster = $cluster
ServerVendor= $server_vendor
Region = $region

[mq]
MainNatsURL = sdk.nats.packetsdk.io
TunNatsURL = $tun_nats_url
EOF
    
    log_info "配置文件创建完成:"
    cat sdk_tun.ini
    cd ..
}

# 安装并启动服务
install_and_start_service() {
    local target_dir="$1"
    cd "$target_dir"
    
    if [ ! -f "quic_tunnel" ]; then
        log_error "quic_tunnel程序不存在"
        return 1
    fi
    
    log_info "安装服务..."
    if ./quic_tunnel install; then
        log_info "服务安装成功"
    else
        log_warn "服务安装返回警告，继续启动流程..."
    fi

    log_info "直接启动服务..."
    if ./quic_tunnel start; then
        log_info "服务启动命令执行成功"
    else
        log_warn "服务启动命令执行返回警告，继续检查状态..."
    fi    
    
    sleep 5
}

# 显示服务状态
show_status() {
    echo
    log_info "=== 服务状态 ==="
    
    if pgrep -f "quic_tunnel" > /dev/null; then
        log_info "✓ quic_tunnel进程运行中"
        echo "进程信息:"
        ps aux | grep quic_tunnel | grep -v grep | head -5
    else
        log_error "✗ quic_tunnel进程未运行"
    fi
    
    local log_file=$(find /root/quic_tunnel -name "quic_tunnel.*.log" -type f -printf "%T@ %p\n" 2>/dev/null | sort -n | tail -1 | cut -d' ' -f2-)
    
    if [ -n "$log_file" ] && [ -f "$log_file" ]; then
        echo
        log_info "最新日志片段:"
        tail -10 "$log_file" | while read line; do
            if echo "$line" | grep -q "ERRO"; then
                echo -e "${RED}$line${NC}"
            elif echo "$line" | grep -q "WARN"; then
                echo -e "${YELLOW}$line${NC}"
            else
                echo "$line"
            fi
        done
    else
        log_warn "未找到日志文件"
    fi
}

# 显示当前配置
show_current_config() {
    if [ -f "/root/quic_tunnel/sdk_tun.ini" ]; then
        echo
        log_info "当前配置文件:"
        echo "=========================================="
        cat /root/quic_tunnel/sdk_tun.ini
        echo "=========================================="
    else
        log_warn "未找到配置文件"
    fi
}

# 配置参数输入
get_config() {
    echo
    log_info "请配置quic_tunnel参数"
    echo "=========================================="
    
    # Cluster配置
    read -p "请输入集群名称 [默认: bloom]: " Cluster
    Cluster=${Cluster:-bloom}
    
    # ServerVendor配置
    echo "可选服务器供应商:"
    echo "1) tencent  2) huawei  3) ali  4) ucloud"
    echo "5) huoshan  6) zenlayer 7) ocean 8) oracle 9) test"
    read -p "请选择服务器供应商编号 (1-9, 默认9): " vendor_choice
    
    case $vendor_choice in
        1) ServerVendor="tencent" ;;
        2) ServerVendor="huawei" ;;
        3) ServerVendor="ali" ;;
        4) ServerVendor="ucloud" ;;
        5) ServerVendor="huoshan" ;;
        6) ServerVendor="zenlayer" ;;
        7) ServerVendor="ocean" ;;
        8) ServerVendor="oracle" ;;
        9|"") ServerVendor="test" ;;
        *) ServerVendor="test" ;;
    esac
    
    # Region配置
    echo "可选区域:"
    echo "1) na  2) as  3) eu  4) va"
    read -p "请选择区域编号 (1-4, 默认3): " region_choice
    
    case $region_choice in
        1) Region="na" ;;
        2) Region="as" ;;
        3|"") Region="eu" ;;
        4) Region="va" ;;
        *) Region="eu" ;;
    esac
    
    # TunNatsURL配置
    local default_nats_url=127.0.0.1:4222
    read -p "请输入隧道Nats服务器URL [默认: $default_nats_url]: " TunNatsURL
    TunNatsURL=${TunNatsURL:-$default_nats_url}
}

# ========== 部署功能部分 ==========

# 快速部署
quick_deploy() {
    log_info "开始快速部署..."
    
    mkdir -p /root/quic_tunnel
    download_files "/root/quic_tunnel"
    create_config "bloom" "test" "eu" "127.0.0.1:4222"
    install_and_start_service "/root/quic_tunnel"
}

# 交互式部署
interactive_deploy() {
    log_info "开始交互式部署..."
    
    get_config
    
    mkdir -p /root/quic_tunnel
    download_files "/root/quic_tunnel"
    create_config "$Cluster" "$ServerVendor" "$Region" "$TunNatsURL"
    install_and_start_service "/root/quic_tunnel"
}

# 重启服务
restart_service() {
    log_info "重启服务..."
    
    if ! check_quic_dir; then
        return 1
    fi
    
    cd /root/quic_tunnel
    
    if [ ! -f "quic_tunnel" ]; then
        log_error "quic_tunnel程序不存在"
        return 1
    fi
    
    safe_stop_service
    ./quic_tunnel start
    return 0
}

# ========== 主菜单和入口 ==========

# 主菜单
main_menu() {
    while true; do
        echo
        log_info "QUIC隧道服务部署脚本"
        echo "========================================"
        echo "1. 快速部署（使用默认配置，请先修改quick_deploy配置）"
        echo "2. 交互式部署（可选择配置）"
        echo "3. 重启服务"
        echo "4. 清理服务"
        echo "5. 查看状态"
        echo "6. 查看配置"
        echo "7. 退出"
        echo
        
        read -p "请选择操作 (1-7): " choice
        
        if [ -z "$choice" ]; then
            log_error "请输入有效数字"
            continue
        fi
        
        case $choice in
            1)
                quick_deploy
                show_status
                ;;
            2)
                interactive_deploy
                show_status
                ;;
            3)
                if restart_service; then    
                    show_status
                fi
                ;;
            4)
                complete_cleanup
                ;;            
            5)
                if check_quic_dir; then
                    show_status
                fi
                ;;
            6)
                if check_quic_dir; then
                    show_current_config
                fi
                ;;
            7)
                log_info "退出脚本"
                exit 0
                ;;
            *)
                log_error "无效选择"
                ;;
        esac
        
        echo
        read -p "按回车键继续..." dummy
    done
}

# 脚本入口
if [ "$1" = "auto" ]; then
    quick_deploy
    show_status
elif [ "$1" = "clean" ]; then
    complete_cleanup
elif [ "$1" = "status" ]; then
    show_status
else
    main_menu
fi